import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "layout",
    redirect: "/home",
    component: () =>
      import(/* webpackChunkName: "layout" */ "@/views/layout/layoutView.vue"),
    children: [
      {
        path: "/home",
        name: "home",
        component: () =>
          import(/* webpackChunkName: "home" */ "@/views/home/homeView.vue"),
      },
      {
        path: "/list/manage",
        name: "listManage",
        redirect: "/list/manage/lists",
        component: () =>
          import(
            /* webpackChunkName: "listManage" */ "@/views/listManage/listManageView.vue"
          ),
        children: [
          {
            path: "lists",
            name: "list",
            component: () => import("@/views/lists/ListView.vue"),
          },
          {
            path: "add",
            name: "listAdd",
            component: () => import("@/views/listAdd/listAdd.vue"),
          },
        ],
      },
      {
        path: "/set",
        name: "set",
        component: () =>
          import(/* webpackChunkName: "set" */ "@/views/set/setView.vue"),
      },
    ],
  },
  {
    path: "/login",
    name: "login",
    component: () =>
      import(/* webpackChunkName: "login" */ "@/views/login/loginView.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem("token");

  if (token) {
    if (to.path === "/login") {
      next("/");
    } else {
      next();
    }
  } else {
    if (to.path === "/login") {
      next();
    } else {
      next("/login");
    }
  }
});

export default router;
